package net.keebook.webapp.util;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import net.keebook.webapp.entity.ItemGroup;
import net.keebook.webapp.entity.PasswordItem;
import au.com.bytecode.opencsv.CSVWriter;

public class ExportCsv extends DatabaseExport {
	@Override
	public void export() throws IOException {
		Writer out = new OutputStreamWriter(getOutputStream());
		CSVWriter csvWriter = new CSVWriter(out, ';');
		
		String[] headlines = {"Title", "Group", "Username", "Password", "URL"};
		csvWriter.writeNext(headlines);
		
		for (PasswordItem item : getItems()) {
			String[] tokens = new String[5];
			tokens[0] = item.getTitle();
			tokens[1] = "";
			if (item.getGroup() instanceof ItemGroup) {
				tokens[1] = item.getGroup().getTitle();
			}
			tokens[2] = item.getUsername();
			tokens[3] = item.getPassword();
			tokens[4] = item.getUrl();
			csvWriter.writeNext(tokens);
		}
		csvWriter.close();
	}

	@Override
	public String getFileExtension() {
		return "csv";
	}
}
